package com.bplow.deep.base.concurrent.synclock;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

public class AnnotationSyncLockAttributeSource implements SyncLockAttributeSource{
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private final static SyncLockAttribute NULL_CACHING_ATTRIBUTE = new SyncLockAttribute();
	
	private final Set<SyncLockAnnotationParser> annotationParsers;
	
	final Map<Object, SyncLockAttribute> attributeCache = new ConcurrentHashMap<Object, SyncLockAttribute>(1024);
	
	public AnnotationSyncLockAttributeSource() {
		
		this.annotationParsers = new LinkedHashSet<SyncLockAnnotationParser>(2);
		this.annotationParsers.add(new SyncLockAnnotationParser());
		
	}
	
	@Override
	public SyncLockAttribute getSyncLockAttribute(Method method, Class<?> targetClass) {
		
		Object cacheKey = getCacheKey(method, targetClass);
		Object cached = this.attributeCache.get(cacheKey);
		if (cached != null) {
			// Value will either be canonical value indicating there is no transaction attribute,
			// or an actual transaction attribute.
			
			if (cached == NULL_CACHING_ATTRIBUTE) {
				return null;
			}
			else {
				return (SyncLockAttribute) cached;
			}
			
		}
		else {
			// We need to work it out.
			SyncLockAttribute txAtt = computeTransactionAttribute(method, targetClass);
			// Put it in the cache.
			if (txAtt == null) {
				this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE);
			}
			else {
				if (logger.isDebugEnabled()) {
					Class<?> classToLog = (targetClass != null ? targetClass : method.getDeclaringClass());
					logger.debug("Adding transactional method '" + classToLog.getSimpleName() + "." +
							method.getName() + "' with attribute: " + txAtt);
				}
				this.attributeCache.put(cacheKey, txAtt);
			}
			return txAtt;
		}
		
	}
	
	private SyncLockAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {

		// Ignore CGLIB subclasses - introspect the actual user class.
		Class<?> userClass = ClassUtils.getUserClass(targetClass);
		// The method may be on an interface, but we need attributes from the target class.
		// If the target class is null, the method will be unchanged.
		Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
		// If we are dealing with method with generic parameters, find the original method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

		// First try is the method in the target class.
		SyncLockAttribute txAtt = findTransactionAttribute(specificMethod);
		if (txAtt != null) {
			return txAtt;
		}

		// Second try is the transaction attribute on the target class.
		txAtt = findTransactionAttribute(specificMethod.getDeclaringClass());
		if (txAtt != null) {
			return txAtt;
		}

		if (specificMethod != method) {
			// Fallback is to look at the original method.
			txAtt = findTransactionAttribute(method);
			if (txAtt != null) {
				return txAtt;
			}
			// Last fallback is the class of the original method.
			return findTransactionAttribute(method.getDeclaringClass());
		}
		return null;
	}
	
	protected SyncLockAttribute findTransactionAttribute(Method method) {
		return determineTransactionAttribute(method);
	}

	protected SyncLockAttribute findTransactionAttribute(Class<?> clazz) {
		return determineTransactionAttribute(clazz);
	}
	
	protected SyncLockAttribute determineTransactionAttribute(AnnotatedElement ae) {
		for (SyncLockAnnotationParser annotationParser : this.annotationParsers) {
			SyncLockAttribute attr = annotationParser.parseTransactionAnnotation(ae);
			if (attr != null) {
				return attr;
			}
		}
		return null;
	}
	
	protected Object getCacheKey(Method method, Class<?> targetClass) {
		return new DefaultCacheKey(method, targetClass);
	}
	
	private static class DefaultCacheKey {

		private final Method method;

		private final Class<?> targetClass;

		public DefaultCacheKey(Method method, Class<?> targetClass) {
			this.method = method;
			this.targetClass = targetClass;
		}

		@Override
		public boolean equals(Object other) {
			if (this == other) {
				return true;
			}
			if (!(other instanceof DefaultCacheKey)) {
				return false;
			}
			DefaultCacheKey otherKey = (DefaultCacheKey) other;
			return (this.method.equals(otherKey.method) &&
					ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass));
		}

		@Override
		public int hashCode() {
			return this.method.hashCode() + (this.targetClass != null ? this.targetClass.hashCode() * 29 : 0);
		}
	}

}
